package com.heima.user.service.impl;

import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserRelationService;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Slf4j
@Service
public class ApUserRelationServiceImpl implements ApUserRelationService {

    @Autowired
    private CacheService cacheService;

    /**
     * 用户关注 or 取消关注
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //1 检查参数
        if (dto.getOperation() == null || dto.getOperation() < 0 || dto.getOperation() > 1){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2 判断用户是否登录
        ApUser apUser = AppThreadLocalUtil.getUser();
        if(apUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3 关注行为 涉及redis两个key
        Integer authorId = dto.getAuthorId();
        if(dto.getOperation() == 0){//关注
            //将对方写入我的关注中
            cacheService.zAdd(BehaviorConstants.APUSER_FOLLOW_RELATION + apUser.getId().toString(),authorId.toString(),System.currentTimeMillis());

            //将我写如对方的粉丝中
            cacheService.zAdd(BehaviorConstants.APUSER_FOLLOW_RELATION + authorId.toString(),apUser.getId().toString(),System.currentTimeMillis());
        }else {
            //取消关注 同样删除两个key
            cacheService.zRemove(BehaviorConstants.APUSER_FOLLOW_RELATION + apUser.getId().toString(),authorId.toString());
            cacheService.zRemove(BehaviorConstants.APUSER_FOLLOW_RELATION + authorId.toString(),apUser.getId().toString());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
